package com.marquisx.tzdice;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.marquisx.tzdice.model.DiceRecord;

public class DiceRecordAdapter extends BaseAdapter
{
	private ArrayList<DiceRecord> recordList = new ArrayList<DiceRecord>();
	private Context context;
	private int recordMax;
	
	public DiceRecordAdapter(Context context)
	{
		this.context = context;
		this.recordMax = Constants.RECORD_ITEM_MAXIMUM;
	}
	
	@Override
	public int getCount()
	{
		return recordList.size();
	}

	@Override
	public DiceRecord getItem(int position)
	{
		return recordList.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		DiceRecord currentRecord = recordList.get(position);
		
		LayoutInflater factory = LayoutInflater.from(context);
		View recordContainer = factory.inflate(R.layout.record_widget_01, null);
		
		ImageView userProficePicIView = (ImageView)recordContainer.findViewById(R.id.record_user_profile_pic);
		userProficePicIView.setTag(currentRecord.getId());
		userProficePicIView.setImageResource(currentRecord.getUserProfileId());
		
		TextView recordHeaderTV = (TextView)recordContainer.findViewById(R.id.record_header);
		recordHeaderTV.setTextSize(Setting.getTextSize(context));
		recordHeaderTV.setText(currentRecord.getUsername() + " " + context.getResources().getString(currentRecord.getType().getStringId()));
		
		TextView recordContentTV = (TextView)recordContainer.findViewById(R.id.record_content);
		recordContentTV.setTextSize(Setting.getTextSize(context));
		recordContentTV.setText(currentRecord.getContent());
		
		TextView recoredResultTV = (TextView)recordContainer.findViewById(R.id.record_result_view);
		recoredResultTV.setText(currentRecord.getResult());

		return recordContainer;
	}
	
	@Override
	public boolean areAllItemsEnabled()
	{
		return false;
	}

	@Override
	public boolean isEnabled(int position)
	{
		return false;
	}
	
	public void refresh()
	{
		notifyDataSetChanged();
	}
	
	public void setRecordMaximum(int max)
	{
		this.recordMax = max;
	}
	
	public int getRecordMaximum()
	{
		return this.recordMax;
	}
	
	public void clearRecords()
	{
		recordList.clear();
		notifyDataSetChanged();
	}
	
	public void addRecord(DiceRecord record)
	{
		if( recordList.size() >= recordMax )
		{//remove the oldest one
			recordList.remove(0);
		}
		
		recordList.add(record);
		notifyDataSetChanged();
	}
	
}